import { sumBy } from "lodash-es";
import { storeToRefs } from "pinia";
import { useMarketStore } from "../../cache/MarketStore";
import type { Contract, ContractItem } from "../../repositories/contracts/entity";
import type { Price } from "../../cache/MarketStore";

export const useContract = () => {
  const marketStore = useMarketStore();
  const { typePrices } = storeToRefs(marketStore);

  const calcTotalPrice = (
    contract: Contract | ContractItem[],
    priceGetter: (price: Price) => number | undefined
  ): number => {
    let items: ContractItem[] | undefined = contract as unknown as ContractItem[];
    if (!Array.isArray(contract)) {
      items = contract.items;
    }
    return (
      sumBy(
        items?.map((item) => {
          const price = typePrices.value?.get(item.type_id!);
          if (!price || !item.quantity) return 0;
          const selectPrice = priceGetter(price);
          if (!selectPrice) return 0;
          return selectPrice * item.quantity;
        })
      ) ?? []
    );
  };

  return { calcTotalPrice };
};
